class HeartRateService : LifecycleService(), SensorEventListener {
    private lateinit var sensorManager: SensorManager
    private var heartRateSensor: Sensor? = null
    
    override fun onCreate() {
        super.onCreate()
        sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
        heartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE)
        
        // 创建前台服务通知
        val notification = NotificationCompat.Builder(this, "heart_rate_channel")
            .setContentTitle("心率监测中")
            .setSmallIcon(R.drawable.ic_heart)
            .build()
        
        startForeground(1, notification)
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        heartRateSensor?.let {
            sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_NORMAL)
        }
        return super.onStartCommand(intent, flags, startId)
    }
    
    override fun onDestroy() {
        sensorManager.unregisterListener(this)
        super.onDestroy()
    }
    
    override fun onSensorChanged(event: SensorEvent) {
        val heartRate = event.values[0].toInt()
        Log.d("HeartRateService", "当前心率: $heartRate ${System.currentTimeMillis()}")
        
        if(BuildConfig.DEBUG) {
            Toast.makeText(this, "心率:$heartRate", Toast.LENGTH_SHORT).apply {
                setGravity(Gravity.CENTER, 0, 0)
                show()
            }
        }
    }
    
    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
}